from PySide.QtGui import QDialog, QStringListModel, QStandardItemModel, QStandardItem, QMessageBox
from PySide.QtCore import QObject, SIGNAL
from ui_MainWindow import Ui_MainWindow
import os, threading
from datetime import datetime
from bettybox.Document import Document
from bettybox.BettyBox import BettyBoxConfigurator


class MainWindow(QDialog):

  def __init__(self, config_file, parent=None):
    super(MainWindow, self).__init__(parent)

    # Initialize Betty
    print "Configure Betty..."
    configurator = BettyBoxConfigurator()
    self.betty = configurator.get_betty(config_file)

    # Instantiate UI (generated by QtDesigner)
    print "Configure UI..."
    self.content = Ui_MainWindow()
    self.content.setupUi(self)

    # Bind connectors
    self.content.listDocButton.clicked.connect(self.listScannedDocuments)
    self.content.sendToBettyButton.clicked.connect(self.sendToBettyAsync)
    QObject.connect(self.content.listView, SIGNAL('clicked(QModelIndex)'), self.selectDocument)

    # Bind models
    self.docModel = QStandardItemModel()
    self.content.listView.setModel(self.docModel)

  def selectDocument(self, index):
    doc = self.docModel.item(index.row()).data()
    self.content.docSizeEdit.setText('%d kb' % (doc.size /1024))
    self.content.docDateEdit.setText(doc.timestamp.strftime('%y/%m/%d %H:%M:%S'))
    self.content.docTitleEdit.setText(doc.title)

  def sendToBettyAsync(self):
    self.content.progressBar.setMaximum(self.docModel.rowCount())
    self.content.progressBar.setValue(0)
    def callback(msg):
      print "Message:", msg
      if msg == 'Done' or msg == 'Ignored':
        self.content.progressBar.setValue(self.content.progressBar.value() + 1)
    def sendToBetty():
      print "Sending documents to betty"
      for doc in map(lambda x : self.docModel.item(x).data(), xrange(self.docModel.rowCount())):
        self.betty.send_document(doc, callback)
      print "Done"
      #self.displayMessageBox("Betty successfully add documents to the store.")
    thread = threading.Thread(target=sendToBetty)
    thread.start()

  def displayMessageBox(self, text):
    box = QMessageBox()
    box.setText(text)
    box.setWindowTitle("BettyBox")
    box.setIcon(QMessageBox.Information)
    box.show()

  def listScannedDocuments(self):
    # TODO: Move path to settings
   inboxPath = '/Users/guillaume/Documents/BettyBox/In'
   self.docModel.clear()
   for root, dirs, files in os.walk(inboxPath):
     for file in filter(lambda x: x.endswith('.pdf'), files):
       doc = Document.from_file(os.path.join(root, file))
       docItem = QStandardItem(file)
       docItem.setData(doc)
       self.docModel.appendRow(docItem)
